package com.zyz.M_File和IO流.IO流.节点流.Reader和Writer;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author: vick
 * @Date: 2025/4/8
 * @Description:
 * @version: 1.0
 */
public class FileCopy {
    public static void main(String[] args) {
        FileReader fileReader = null;
        FileWriter fileWriter = null;

        try {
            //1. 创建File对象
            File source = new File("hello.txt");
            File target = new File("copy.txt");

            //2. 创建流对象
            fileReader = new FileReader(source);
            fileWriter = new FileWriter(target);

            //3. 读取数据
            char[] cbuf = new char[5];
            //记录每次读入的字符个数
            int len;
            while ((len = fileReader.read(cbuf)) != -1) {
                //写入
                fileWriter.write(cbuf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4. 关闭流
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
